#include "databasehelper.h"
#include <QSqlError>//通过text（）函数可以获取数据库错误的详细文本
#include <QMessageBox>//用于创建和显示各种消息对话框的类
#include <QTime>
#include <QDebug>

DatabaseHelper* DatabaseHelper::instance = nullptr;//静态成员变量的初始化

DatabaseHelper::DatabaseHelper(QObject *parent) : QObject(parent) {
    // 初始化数据库连接
    if (QSqlDatabase::contains(CONN_NAME)) {
        db = QSqlDatabase::database(CONN_NAME);
    } else {
        db = QSqlDatabase::addDatabase("QSQLITE", CONN_NAME);
        db.setDatabaseName(DB_NAME);
    }

    // 打开数据库
    if (!db.open()) {
        QMessageBox::critical(nullptr, "数据库错误", "打开数据库失败：" + db.lastError().text());
    }
}

DatabaseHelper* DatabaseHelper::getInstance(QObject *parent) {
    if (!instance) {
        instance = new DatabaseHelper(parent);
    }
    return instance;
}

DatabaseHelper::~DatabaseHelper() {
    if (db.isOpen()) {
        db.close();
    }

}

bool DatabaseHelper::isOpen() const {
    return db.isOpen();
}

bool DatabaseHelper::createTables() {
    QSqlQuery query(db);
    // 创建搜索列表
    QString sql = "create table if not exists searchlist("
                  "id integer, songname text, singername text, album_id text, hash text)";
    if (!query.exec(sql)) {
        QMessageBox::critical(nullptr, "创建表错误", "searchlist: " + db.lastError().text());
        return false;
    }

    // 创建历史记录表
    sql = "create table if not exists historysong("
          "id integer primary key autoincrement, songname text, singername text, album_id text, hash text)";
    if (!query.exec(sql)) {
        QMessageBox::critical(nullptr, "创建表错误", "historysong: " + db.lastError().text());
        return false;
    }
    return true;
}

bool DatabaseHelper::clearSearchList() {
    QSqlQuery query(db);
    if (!query.exec("delete from searchlist")) {
        qDebug() << "清空搜索列表失败：" << db.lastError().text();
        return false;
    }
    return true;
}

bool DatabaseHelper::insertSearchSong(const SongInfo& song) {
    QSqlQuery query(db);
    QString sql = QString("insert into searchlist VALUES(%1,'%2','%3','%4','%5')")
                      .arg(song.id).arg(song.songname).arg(song.singername)
                      .arg(song.album_id).arg(song.hash);
    if (!query.exec(sql)) {
        qDebug() << "插入搜索歌曲失败：" << db.lastError().text();
        return false;
    }
    return true;
}

SongInfo DatabaseHelper::querySearchSongByRow(int row) {
    SongInfo song;
    QSqlQuery query(db);//创建 QSqlQuery 对象并关联数据库连接 db
    if (query.exec(QString("select * from searchlist where id=%1").arg(row))) {
        if (query.next()) {
            song.id = row;
            song.songname = query.value("songname").toString();
            song.singername = query.value("singername").toString();
            song.album_id = query.value("album_id").toString();
            song.hash = query.value("hash").toString();
        }
    } else {
        qDebug() << "查询搜索歌曲失败：" << db.lastError().text();
    }
    return song;
}

bool DatabaseHelper::insertHistorySong(const SongInfo& song) {
    QSqlQuery query(db);
    // 检查是否已存在
    query.exec(QString("select hash from historysong where hash='%1'").arg(song.hash));
    if (query.next()) return true;

    QString sql = QString("insert into historysong values(NULL,'%1','%2','%3','%4')")
                      .arg(song.songname).arg(song.singername)
                      .arg(song.album_id).arg(song.hash);
    if (!query.exec(sql)) {
        qDebug() << "插入历史歌曲失败：" << db.lastError().text();
        return false;
    }
    return true;
}

QList<SongInfo> DatabaseHelper::queryAllHistorySongs() {
    QList<SongInfo> songs;
    QSqlQuery query(db);
    if (query.exec("select * from historysong")) {
        while (query.next()) {
            SongInfo song;
            song.id = query.value("id").toInt();
            song.songname = query.value("songname").toString();
            song.singername = query.value("singername").toString();
            song.album_id = query.value("album_id").toString();
            song.hash = query.value("hash").toString();
            songs.append(song);
        }
    } else {
        qDebug() << "查询历史歌曲失败：" << db.lastError().text();
    }
    return songs;
}

SongInfo DatabaseHelper::queryHistorySongById(int id) {
    SongInfo song;
    QSqlQuery query(db);
    if (query.exec(QString("select * from historysong where id=%1").arg(id))) {
        if (query.next()) {
            song.id = id;
            song.songname = query.value("songname").toString();
            song.singername = query.value("singername").toString();
            song.album_id = query.value("album_id").toString();
            song.hash = query.value("hash").toString();
        }
    } else {
        qDebug() << "查询历史歌曲失败：" << db.lastError().text();
    }
    return song;
}
